<template>
  <!-- 沉睡气瓶 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="芯片编码:" prop="chipCode">
        <el-input v-model.trim="query.chipCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item class="merge-item" style="display: flex;" :table-form-merge="1">
        <el-select v-model="query.selectType" style="width: 125px; margin-right: 2px;" placeholder="请选择">
          <el-option :value="1" label="最后配送时间" />
          <el-option :value="2" label="最后充装时间" />
        </el-select>
        <span style="flex: 1; display: flex;">
          <span>大于</span>
          <el-input-number v-model.trim="query.sleepingDays" style="flex: 1;" :min="0" :precision="0" :controls="false" />
          <span>天</span>
        </span>
      </el-form-item>
      <el-form-item :table-form-merge="1" class="merge-item" label="最后配送距充装大于:" style="display: flex;">
        <el-input-number v-model.trim="query.daysBetween" :min="0" :precision="0" :controls="false" /> 天
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="orgType" style="width: 170px; margin-right: 2px;" @change="orgTypeChange">
          <el-option :value="1" label="配送机构" />
          <el-option :value="2" label="充装机构" />
        </el-select>
        <el-tree-select
          v-model="orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled'
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select v-model="query.csmType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 20px;">
      <el-button v-permission="4" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
    </div>

    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <chip-detail ref="chipDetail" />
    <historicalTrack ref="historicalTrack" />
  </div>
</template>

<script>
  import { querySleepCylinderList, queryMap, querySleepCylinderExport, queryOrgGasListAll } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import HistoricalTrack from './components/HistoricalTrack'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import ChipDetail from '../../components/BottleDetail'

  export default {
    name: 'sleepCylinderWarn',
    components: {
      HistoricalTrack, ChipDetail
    },
    data() {
      return {
        treeData: [],
        orgGasList: [], // 充装站列表
        orgType: 1,
        orgSNNo: '',
        query: {
          chipCode: '',
          selectType: 1,
          sleepingDays: 30,
          daysBetween: 30,
          csmType: ''
        },
        customerTypeMap: [],
        searchParams: {},
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'chipCode',
              label: '芯片编码',
              width: 150,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openChipDetail(row)}>{row.chipCode}</el-link>
            },
            {
              prop: 'czTime',
              label: '最后充装时间',
              width: 160,
              render: (h, { row }) => <span>{ row.czTime && parseTime(row.czTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'czSleepingDays',
              align: 'right',
              label: '充装距今天数',
              width: 110
            },
            {
              prop: 'czOrgName',
              label: '充装机构',
              width: 150
            },
            {
              prop: 'modifyTime',
              label: '最后配送时间',
              width: 160,
              render: (h, { row }) => <span>{ row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'sleepingDays',
              align: 'right',
              label: '配送距今天数',
              width: 110
            },
            {
              prop: 'csmName',
              label: '最后配送客户',
              width: 110
            },
            {
              prop: 'csmPhone',
              label: '最后配送客户电话',
              width: 135
            },
            {
              prop: 'csmAddress',
              label: '最后配送客户地址',
              width: 200
            },
            {
              prop: 'csmType',
              label: '客户类型',
              width: 110,
              render: (h, { row }) => <span>{ row.csmType ? formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') : '未知' }</span>
            },
            {
              prop: 'orgName',
              label: '配送机构',
              width: 150
            },
            {
              prop: 'sender',
              label: '配送员'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 100,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link v-permission='2' underline={false} size='mini' onClick={() => this.openHistoricalTrack(row, $index)}>
                      气瓶历史踪迹
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },

    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ])
    },
    created() {
      this.getTreeData()
      this.queryOptionsMap()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          pageIndex: currentPage,
          pageSize
        }
        if (this.orgSNNo) {
          const org = this.orgList.find(item => item.orgSNNo === this.orgSNNo)
          if (this.orgType === 1) {
            query.orgName = org.orgName
            query.orgId = org.orgId
            query.orgSNNo = org.orgSNNo
          } else {
            query.czOrgName = org.orgName
            query.czOrgId = org.orgId
            query.czOrgSNNo = org.orgSNNo
          }
        }
        if (!query.sleepingDays && query.sleepingDays !== 0) {
          this.$message.error('天数输入不正确')
          return
        }
        if (!this.query.daysBetween) query.daysBetween = 0
        const res = await querySleepCylinderList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取所属机构数据
      async getTreeData() {
        const arr = this.orgType === 1 ? this.orgList : this.orgGasList
        const data = arr.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        this.customerTypeMap = res.data // 客户类型
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          querySleepCylinderExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 芯片编码
      openChipDetail(row) {
        this.$refs.chipDetail.open(row, 1, 'sleepCylinder')
      },
      // 历史轨迹
      openHistoricalTrack(row) {
        this.$refs.historicalTrack.open(row)
      },
      // 机构类型改变
      async orgTypeChange(value) {
        this.orgSNNo = ''
        if (value === 2) {
          const res = await queryOrgGasListAll()
          this.orgGasList = res.data
        }
        this.getTreeData()
      }
    }
  }
</script>

<style lang='scss' scoped>
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
</style>
